-- SPDX-License-Identifier: GPL-3.0-or-later

local extension = Package:new("teyvat_cards", Package.CardPack)
extension.extensionName = "zenless__teyvat"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["teyvat_cards"] = "提瓦特卡牌",
}

local beansIntoTroopsSkill = fk.CreateActiveSkill{
  name = "beans_into_troops_skill",
  prompt = "#beans_into_troops_skill",
  mod_target_filter = Util.TrueFunc,
  can_use = function(self, player, card)
    return not player:isProhibited(player, card)
  end,
  on_use = function(self, room, cardUseEvent)
    if not cardUseEvent.tos or #TargetGroup:getRealTargets(cardUseEvent.tos) == 0 then
      cardUseEvent.tos = { { cardUseEvent.from } }
    end
  end,
  on_effect = function(self, room, effect)
    local target = room:getPlayerById(effect.to)
    if target.dead then return end
    local x = target.maxHp - target:getHandcardNum()
    if target.kingdom == "god" or Fk.generals[target.general].kingdom == "god" or Fk.generals[target.general].subkingdom == "god"
    or (target.deputyGeneral ~= "" and (Fk.generals[target.deputyGeneral].kingdom == "god" or Fk.generals[target.deputyGeneral].subkingdom == "god")) then
    target:drawCards(math.min(5, target.maxHp), "beans_into_troops")
    else
      if x > 0 then
      target:drawCards(math.min(5, x), "beans_into_troops")
      end
    end
  end
}

local beansIntoTroops = fk.CreateTrickCard{
  name = "&beans_into_troops",
  suit = Card.Heart,
  number = 7,
  skill = beansIntoTroopsSkill,
}

extension:addCards({
  beansIntoTroops,
})

Fk:loadTranslationTable{
  ["beans_into_troops"] = "撒豆成兵",
  [":beans_into_troops"] = "锦囊牌<br /><b>时机</b>：出牌阶段<br /><b>目标</b>：你。<br /><b>效果</b>：若你的势力或你武将牌上的至少一个势力为神，你摸X张牌；"..
  "否则你将手牌摸至X张（X为你的体力上限且最多为5）。",
  ["#beans_into_troops_skill"] = "对你使用，若你的势力或你武将牌上的至少一个势力为神，你摸体力上限张牌，否则你摸牌至体力上限。（均至多摸五张）",
  ["beans_into_troops_skill"] = "撒豆成兵",
}

local graftFlowerSkill = fk.CreateActiveSkill{
  name = "graft_flower_skill",
  prompt = "#graft_flower_skill",
  can_use = Util.CanUse,
  target_num = 1,
  mod_target_filter = function(self, to_select, selected, player, card)
    return to_select ~= player.id and not Fk:currentRoom():getPlayerById(to_select):isNude()
  end,
  target_filter = Util.TargetFilter,
  on_effect = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.to)
    if from.dead or to.dead then return end
    local use = room:askForUseCard(to, "slash", "slash", "#graft_flower-slash", true, { bypass_times = true })
    if use then
      use.extraUse = true
      room:useCard(use)
    else
      if from.dead or to.dead or to:isNude() then return end
      if #to:getCardIds("he") == 1 then
        local card = room:askForCard(to, 1, 1, true, self.name, false, ".", "#graft_flower-give")
        room:obtainCard(from, card, false, fk.ReasonGive, effect.to, "graft_flower")
      else
        local card = room:askForCard(to, 2, 2, true, self.name, false, ".", "#graft_flower-give")
        room:obtainCard(from, card, false, fk.ReasonGive, effect.to, "graft_flower")
      end
    end
  end
}
local graftFlower = fk.CreateTrickCard{
  name = "&graft_flower",
  suit = Card.Club,
  number = 12,
  skill = graftFlowerSkill,
}

extension:addCards({
  graftFlower,
})

Fk:loadTranslationTable{
  ["graft_flower"] = "移花接木",
  [":graft_flower"] = "锦囊牌<br /><b>时机</b>：出牌阶段<br /><b>目标</b>：一名有牌的其他角色。<br /><b>效果</b>：目标角色选择一项：1.使用一张【杀】；2.交给你两张牌（不足全给）。",
  ["#graft_flower_skill"] = "对一名有牌的其他角色使用。目标角色使用一张【杀】或交给你两张牌。",
  ["graft_flower_skill"] = "移花接木",
  ["#graft_flower-slash"] = "移花接木：请使用一张【杀】，否则交给使用者两张牌。",
  ["#graft_flower-give"] = "移花接木：交给使用者两张牌（不足全给）。",
}

local underhandingSkill = fk.CreateActiveSkill{
  name = "underhanding_skill",
  prompt = "#underhanding_skill",
  can_use = Util.CanUse,
  min_target_num = 1,
  max_target_num = 2,
  mod_target_filter = function(self, to_select, selected, user, card)
    return user ~= to_select and not Fk:currentRoom():getPlayerById(to_select):isAllNude()
  end,
  target_filter = Util.TargetFilter,
  on_effect = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.to)
    if not to:isAllNude() then
      local id = room:askForCardChosen(player, to, "hej", self.name)
      room:obtainCard(player, id, false, fk.ReasonPrey, player.id, self.name)
      local e = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
      if e then
        local use = e.data[1]
        use.extra_data = use.extra_data or {}
        use.extra_data.underhanding_targets = use.extra_data.underhanding_targets or {}
        table.insertIfNeed(use.extra_data.underhanding_targets, to.id)
      end
    end
  end,
  on_action = function (self, room, use, finished)
    if not finished then return end
    local player = room:getPlayerById(use.from)
    if player.dead or player:isNude() then return end
    local targets = (use.extra_data or {}).underhanding_targets or {}
    if #targets == 0 then return end
    room:sortPlayersByAction(targets)
    for _, pid in ipairs(targets) do
      local target = room:getPlayerById(pid)
      if not player:isNude() and not target.dead and not player.dead then
        local c = room:askForCard(player, 1, 1, true, self.name, false, nil, "#underhanding-card::" .. pid)[1]
        room:moveCardTo(c, Player.Hand, target, fk.ReasonGive, self.name, nil, false, player.id)
      end
    end
  end
}
local underhandingExclude = fk.CreateMaxCardsSkill{
  name = "underhanding_exclude",
  global = true,
  exclude_from = function(self, player, card)
    return card and card.name == "underhanding"
  end,
}
Fk:addSkill(underhandingExclude)
local underhanding = fk.CreateTrickCard{
  name = "&underhanding",
  suit = Card.Heart,
  number = 5,
  skill = underhandingSkill,
  multiple_targets = true,
}
extension:addCards{
  underhanding,
}

Fk:loadTranslationTable{
  ["underhanding"] = "瞒天过海",
  [":underhanding"] = "锦囊牌<br /><b>时机</b>：出牌阶段<br /><b>目标</b>：一至两名区域内有牌的其他角色。<br /><b>效果</b>：你依次获得目标角色区域内的一张牌，然后依次交给目标角色一张牌。<br />此牌不计入你的手牌上限。",
  ["underhanding_skill"] = "瞒天过海",
  ["underhanding_action"] = "瞒天过海",
  ["#underhanding-card"] = "瞒天过海：交给 %dest 一张牌",
  ["#underhanding_skill"] = "选择一至两名区域内有牌的其他角色，依次获得其区域内的一张牌，然后依次交给其一张牌",
}

local tey__drowningSkill = fk.CreateActiveSkill{
  name = "tey__drowning_skill",
  prompt = "#tey__drowning_skill",
  min_target_num = 1,
  max_target_num = 2,
  mod_target_filter = Util.TrueFunc,
  target_filter = Util.TargetFilter,
  on_use = function(self, room, cardUseEvent)
    if cardUseEvent.tos == nil or #cardUseEvent.tos == 0 then return end
    cardUseEvent.extra_data = cardUseEvent.extra_data or {}
    cardUseEvent.extra_data.firstTargetOfTeyDrowning = cardUseEvent.tos[1][1]
  end,
  on_effect = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.to)
    room:damage({
      from = from,
      to = to,
      card = effect.card,
      damage = 1,
      damageType = fk.ThunderDamage,
      skillName = self.name
    })
    if not to.dead then
      if effect.extra_data and effect.extra_data.firstTargetOfTeyDrowning == effect.to then
        room:askForDiscard(to, 1, 1, true, self.name, false)
      else
        to:drawCards(1, self.name)
      end
    end
  end
}
local tey__drowning = fk.CreateTrickCard{
  name = "&tey__drowning",
  skill = tey__drowningSkill,
  is_damage_card = true,
  suit = Card.Spade,
  number = 6,
}
extension:addCard(tey__drowning)
Fk:loadTranslationTable{
  ["tey__drowning"] = "水淹七军",
  ["tey__drowning_skill"] = "水淹七军",
  [":tey__drowning"] = "锦囊牌<br/><b>时机</b>：出牌阶段<br/><b>目标</b>：一至两名角色<br /><b>效果</b>："..
  "第一名角色受到1点雷电伤害并弃置一张牌，该角色以外的角色受到1点雷电伤害并摸一张牌",
  ["#tey__drowning_skill"] = "选择1-2名目标角色，第一名角色受到1点雷电伤害并摸牌，第二名角色受到1点雷电伤害并弃牌",
}

--[[
原始名称
焚曜千阳 A Thousand Blazing Suns
祭星者之望 Starcaller's Watch  
星鹫赤羽 Astral Vulture's Crimson Plumage 
暗巷猎手 Alley Hunter 
山王长牙 Fang of the Mountain King	
岩峰巡歌 Peak Patrol Song 
镇山之钉 Mountain-Bracing Bolt 
冲浪时光 Surf's Up 
溢彩心念 Vivid Notions

玛薇卡专武 a_thousand_blazing_suns ✔ ✔
茜特拉莉专武 starcaller_watch ✔ ✔
恰斯卡专武 astral_vulture_crimson_plumage ✔ ✔
欧洛伦的并非专武 alley_hunter ✔ ✔
基尼奇专武 fang_of_mountain_king ✔ ✔
希诺宁专武 peak_patrol_song ✔ ✔
卡齐娜专武 mountain_bracing_bolt ✔ ✔
玛拉妮专武 surf_up ✔ ✔
瓦蕾莎专武 vivid_notions ✔ ✔

暂无 伊安珊专武
]]

local tey__cangrong_destruct = fk.CreateTriggerSkill{ --销毁规则，除了苍熔置入，只要发生移动就销毁
  name = "#tey__cangrong_destruct",
  frequency = Skill.Compulsory,

  refresh_events = {fk.BeforeCardsMove},
  can_refresh = function(self, event, target, player, data)
    local natlan_weapons_name = {
      "a_thousand_blazing_suns", "astral_vulture_crimson_plumage",
      "peak_patrol_song", "vivid_notions",
      "starcaller_watch",
      "surf_up", "fang_of_mountain_king",
      "mountain_bracing_bolt","alley_hunter",
    }
    return table.find(player:getCardIds("hej"), function (id)
      return table.contains(natlan_weapons_name, Fk:getCardById(id).name)
    end)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local natlan_weapons_name = {
      "a_thousand_blazing_suns", "astral_vulture_crimson_plumage",
      "peak_patrol_song", "vivid_notions",
      "starcaller_watch",
      "surf_up", "fang_of_mountain_king",
      "mountain_bracing_bolt","alley_hunter",
    }
    local mirror_moves = {}
    local to_void = {}
    for _, move in ipairs(data) do
      if move.from == player.id and move.toArea ~= Card.Void then
        local move_info = {}
        local mirror_info = {}
        for _, info in ipairs(move.moveInfo) do
          local id = info.cardId
          local cardname = Fk:getCardById(id).name
          if table.contains(natlan_weapons_name, cardname) 
           and (info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerJudge or
           (info.toArea ~= Card.PlayerEquip and info.fromArea == Card.PlayerHand)) then
            local banner = room:getBanner("@$natlan_weapons_destructed")
            local names = {}
            if banner ~= nil then
              for _, p in ipairs(banner) do
                local card = Fk:getCardById(p)
                table.insertIfNeed(names, Fk:getCardById(p).name)
              end
              if not table.contains(names, cardname) and cardname ~= "alley_hunter" then
               table.insertIfNeed(banner, id)
               room:setBanner("@$natlan_weapons_destructed", banner ~= nil and banner or {})
              end
            else
              if cardname ~= "alley_hunter" then
              room:setBanner("@$natlan_weapons_destructed", {id})
              end
            end
              table.insert(mirror_info, info)
              table.insert(to_void, id)
            else
              table.insert(move_info, info)
            end
          end
        move.moveInfo = move_info
        if #mirror_info > 0 then
          local mirror_move = table.clone(move)
          mirror_move.to = nil
          mirror_move.toArea = Card.Void
          mirror_move.moveInfo = mirror_info
          table.insert(mirror_moves, mirror_move)
        end
      end
    end
    if #to_void > 0 then
      table.insertTable(data, mirror_moves)
      player.room:sendLog{ type = "#destructDerivedCards", card = to_void, }
    end
  end,
} 

Fk:loadTranslationTable{
  ["#tey__cangrong_destruct"] = "苍熔",
  ["@$natlan_weapons_destructed"] = "已毁纳塔武器",
}

local aThousandBlazingSunsSkill = fk.CreateTriggerSkill{
  name = "#aThousandBlazingSunsSkill",
  attached_equip = "a_thousand_blazing_suns",
  frequency = Skill.Compulsory,
  events = {fk.AfterSkillEffect},
  can_trigger = function(self, _, target, player, data)
    return player:hasSkill(self) and data ~= self
    and target == player and player:hasSkill(data, true)
    and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, _, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
    "#aThousandBlazingSuns-ask", self.name, false)
    if #to > 0 then
      room:damage{
        from = player,
        to = room:getPlayerById(to[1]),
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
    end
    if not player.dead then
      room:loseHp(player, 1, self.name)
    end
  end,
}

local a_thousand_blazing_suns = fk.CreateWeapon{
  name = "&a_thousand_blazing_suns",
  suit = Card.Heart,
  number = 12,
  attack_range = 3,
  equip_skill = aThousandBlazingSunsSkill,
}

Fk:loadTranslationTable{
  ["a_thousand_blazing_suns"] = "焚曜千阳",
  [":a_thousand_blazing_suns"] = "装备牌·武器<br /><b>攻击范围</b>：3<br /><b>武器技能</b>：锁定技，每阶段限一次，"..
  "你发动武将或装备技能后，对另一名角色造成1点火焰伤害，然后失去1点体力。",
  ["#aThousandBlazingSunsSkill"] = "焚曜千阳",
  ["#aThousandBlazingSuns-ask"] = "焚曜千阳：对一名其他角色造成1点火焰伤害，然后你失去1点体力！",
}

extension:addCard(a_thousand_blazing_suns)
aThousandBlazingSunsSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(aThousandBlazingSunsSkill)

local starcallerWatchSkill = fk.CreateTriggerSkill{
  name = "#starcallerWatchSkill",
  attached_equip = "starcaller_watch",
  events = {fk.EventPhaseStart, fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return target == player and player:hasSkill(self) and player.phase == Player.Play and 
      #table.filter(player:getCardIds("he"), function(id) return not player:prohibitDiscard(Fk:getCardById(id)) end) >= 2
    elseif event == fk.CardUsing then
    return target == player and data.card.is_damage_card and player:getMark("@@starcaller_watch-phase") > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return player.room:askForSkillInvoke(player, self.name, nil, "#starcaller_watch-invoke")
    elseif event == fk.CardUsing then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local bas = room:askForDiscard(player, 2, 2, true, self.name, false, ".", "#starcaller_watch-ask")
      if #bas == 2 then
        room:setPlayerMark(player, "@@starcaller_watch-phase", 1)
      end
    elseif event == fk.CardUsing then
      room:setPlayerMark(player, "@@starcaller_watch-phase", 0)
      local x = 0
      x = x + player:getHandcardNum()
      for _, p in ipairs(room:getAllPlayers()) do
        if p:getHandcardNum() == x and p.shield <= 0 then
          room:changeShield(p, 1)
        end
      end
    end
  end,
}

local starcaller_watch = fk.CreateWeapon{
  name = "&starcaller_watch",
  suit = Card.Spade,
  number = 9,
  attack_range = 2,
  equip_skill = starcallerWatchSkill,
}

Fk:loadTranslationTable{
  ["starcaller_watch"] = "祭星者之望",
  [":starcaller_watch"] = "装备牌·武器<br /><b>攻击范围</b>：2<br /><b>武器技能</b>：出牌阶段开始时，你可以弃置两张牌，然后你本阶段下次使用伤害牌时，"..
  "手牌数等于你的角色各将护甲补至1点。",
  ["#starcallerWatchSkill"] = "祭星者之望",
  ["#starcaller_watch-invoke"] = "祭星者之望：是否发动本技能？（此后下次使用伤害牌时，与手牌数等于你的角色获得护甲）",
  ["#starcaller_watch-ask"] = "祭星者之望：请弃置两张牌！",
  ["@@starcaller_watch-phase"] = "祭星 加护甲",
}
extension:addCard(starcaller_watch)
starcallerWatchSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(starcallerWatchSkill)

local alleyHunterSkill = fk.CreateTriggerSkill{
  name = "#alleyHunterSkill",
  frequency = Skill.Compulsory,
}

alleyHunterSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(alleyHunterSkill)

local alley_hunter = fk.CreateWeapon{
  name = "&alley_hunter",
  suit = Card.NoSuit,
  number = 0,
  attack_range = 5,
  equip_skill = alleyHunterSkill,
  ---@param room Room
  on_install = function(self, room, player)
    if player:isAlive() and self.equip_skill:isEffectable(player) then
      if not player:hasSkill("tey__baoju", true) then --强行加载一次希诺宁的本体然后删除，代替加载暗巷猎手的技能
      room:handleAddLoseSkills(player, "tey__baoju", nil, false, true)
      room:handleAddLoseSkills(player, "-tey__baoju", nil, false, true)
      room:handleAddLoseSkills(player, tey__cangrong_destruct.name, nil, false, true)
      room:handleAddLoseSkills(player, "-"..tey__cangrong_destruct.name, nil, false, true)
      end
      if player:getMark("__hidden_general") == 0 and player:getMark("__hidden_deputy") == 0 then
        IntoHidden(player) --防止双将反复嵌套进入隐匿顶替掉主将的数据
        room:setPlayerMark(player, "@@alley_hunter", true)
      end
    end
  end,
}

Fk:loadTranslationTable{
  ["alley_hunter"] = "暗巷猎手",
  [":alley_hunter"] = "装备牌·武器<br /><b>攻击范围</b>：5<br /><b>武器技能</b>：锁定技，此牌置入你的装备区时，你隐匿并跳过下个弃牌阶段。"..
  "你于回合外登场后，将手牌调整至两张。<br><font color=\"blue\">注：该武器由于发动时机不能在卡牌包加载，效果为伪实现，请勿反馈武器技能的问题。</font>",
  ["@@alley_hunter"] = "暗巷猎手 跳弃",
  ["#alleyHunterSkill"] = "暗巷猎手",
  ["alleyHunterSkill"] = "暗巷猎手",
}

extension:addCard(alley_hunter)

local mountainBracingBoltSkill = fk.CreateActiveSkill{
  name = "mountainBracingBoltSkill",
  anim_type = "switch",
  attached_equip = "mountain_bracing_bolt",
  prompt = "#mountain_bracing_bolt-invoke",
  min_card_num = 1,
  max_card_num = 5,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = function(self, to_select, selected)
    return not Self:prohibitDiscard(Fk:getCardById(to_select)) and #selected <= 5 and table.contains(Self:getCardIds("h"), to_select)
  end,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    if from.dead then return end
    room:setPlayerMark(from, "@mountain_bracing_bolt-phase", #effect.cards)
    room:throwCard(effect.cards, self.name, from, from)
      if not from.dead then
        from:drawCards(2, self.name)
      end
  end,
}

local mountain_bracing_bolt = fk.CreateWeapon{
  name = "&mountain_bracing_bolt",
  suit = Card.NoSuit,
  number = 0,
  attack_range = 1,
  dynamic_attack_range = function(self, player)
    if player then
      local mark = player:getMark("@mountain_bracing_bolt-phase")
      return mark > 0 and mark - 1 or 1
    end
  end,
  equip_skill = mountainBracingBoltSkill,
}
Fk:loadTranslationTable{
  ["mountain_bracing_bolt"] = "镇山之钉",
  [":mountain_bracing_bolt"] = "装备牌·武器<br /><b>攻击范围</b>：1<br /><b>武器技能</b>：出牌阶段限一次，你可以弃置一至五张手牌，"..
  "摸两张牌，将此牌攻击范围改为弃牌数-1直至本阶段结束或失去此牌。",
  ["@mountain_bracing_bolt-phase"] = "镇山之钉",
  ["mountainBracingBoltSkill"] = "镇山之钉",
  [":mountainBracingBoltSkill"] = "出牌阶段限一次，你可以弃置一至五张手牌，摸两张牌，此牌攻击范围改为弃牌数-1直至本阶段结束或失去此牌。",
  ["#mountain_bracing_bolt-invoke"] = "镇山之钉：是否弃置一至五张手牌，攻击范围改为等量，摸两张牌？",
}

extension:addCard(mountain_bracing_bolt)
mountainBracingBoltSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(mountainBracingBoltSkill)

local astralVultureCrimsonPlumageSkill = fk.CreateViewAsSkill{
  name = "astralVultureCrimsonPlumageSkill",
  pattern = "slash",
  card_num = 0,
  prompt = "#astralVultureCrimsonPlumageSkill",
  card_filter = Util.FalseFunc,
  interaction = function(self)
    local allCardNames = {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if
        not table.contains(allCardNames, card.name) and
        card.trueName == "slash" and
        (
          (Fk.currentResponsePattern == nil and Self:canUse(card)) or
          (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card))
        ) and
        not Self:prohibitUse(card) then
        table.insert(allCardNames, card.name)
      end
    end
    return UI.ComboBox { choices = allCardNames }
  end,
  view_as = function(self, cards)
    local choice = self.interaction.data
    if not choice then return end
    local c = Fk:cloneCard(choice)
    c:addSubcards(cards)
    c.skillName = self.name
    return c
  end,
  before_use = function(self, player, use)
    use.extraUse = true
  end,
  enabled_at_play = function(self, player)
    return player:canUse(Fk:cloneCard("slash")) and player:getMark("skill_charge") > 2
  end,
  enabled_at_response = function(self, player, res)
    return Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("slash"))
    and ((res and player:getMark("skill_charge") > 0) or (not res and player:getMark("skill_charge") > 2))
  end,
}
local astralVultureCrimsonPlumageSkill_trigger = fk.CreateTriggerSkill{
  name = "#astralVultureCrimsonPlumageSkill_trigger",
  anim_type = "defensive",
  events = {fk.PreCardUse, fk.PreCardRespond},
  can_trigger = function(self, event, target, player, data)
    return target == player and data.card.skillName == "astralVultureCrimsonPlumageSkill" and data.card.trueName == "slash"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.PreCardUse then
      U.skillCharged(player, -3)
    elseif event == fk.PreCardRespond then
      U.skillCharged(player, -1)
    end
  end,

  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
    return data == astralVultureCrimsonPlumageSkill and target == player
    else
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason ~= fk.ReasonUse and 
        (move.to ~= player.id or (move.toArea ~= Card.PlayerHand and move.toArea ~= Card.PlayerEquip)) then
          for _, info in ipairs(move.moveInfo) do
            return info.fromArea == Card.PlayerHand
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      U.skillCharged(player, 3, 6)
    elseif event == fk.EventLoseSkill then
      U.skillCharged(player, -3, -6)
    elseif event == fk.AfterCardsMove then
      local x = 0
      for _, move in ipairs(data) do
        x = x + #move.moveInfo
      end
      U.skillCharged(player, x)
    end
  end,
}
local astralVultureCrimsonPlumageSkill_targetmod = fk.CreateTargetModSkill{
  name = "#astralVultureCrimsonPlumageSkill_targetmod",
  bypass_times = function(self, player, skill, scope, card)
    return card and scope == Player.HistoryPhase and table.contains(card.skillNames, astralVultureCrimsonPlumageSkill.name)
  end,
}
local astral_vulture_crimson_plumage = fk.CreateWeapon{
  name = "&astral_vulture_crimson_plumage",
  suit = Card.Heart,
  number = 2,
  attack_range = 4,
  equip_skill = astralVultureCrimsonPlumageSkill,
}

Fk:loadTranslationTable{
  ["astral_vulture_crimson_plumage"] = "星鹫赤羽",
  [":astral_vulture_crimson_plumage"] = "装备牌·武器<br /><b>攻击范围</b>：4<br /><b>武器技能</b>：蓄力技（3/6），你可以减少3/1蓄力点，"..
  "视为使用/打出任意无次数限制的【杀】。你不因使用失去手牌后，获得失去牌数的蓄力点。",
  ["astralVultureCrimsonPlumageSkill"] = "星鹫赤羽",
  [":astralVultureCrimsonPlumageSkill"] = "蓄力技（3/6），你可以减少3/1蓄力点，"..
  "视为使用/打出任意无次数限制的【杀】。你不因使用失去手牌后，获得失去牌数的蓄力点。",
  ["#astralVultureCrimsonPlumageSkill"] = "你可以减少3/1蓄力点，视为使用/打出任意无次数限制的【杀】。",
  ["#astralVultureCrimsonPlumageSkill_trigger"] = "星鹫赤羽",
}

extension:addCard(astral_vulture_crimson_plumage)
astralVultureCrimsonPlumageSkill:addRelatedSkill(astralVultureCrimsonPlumageSkill_trigger)
astralVultureCrimsonPlumageSkill:addRelatedSkill(astralVultureCrimsonPlumageSkill_targetmod)
astralVultureCrimsonPlumageSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(astralVultureCrimsonPlumageSkill)

local surfUpSkill = fk.CreateTriggerSkill{
  name = "#surfUpSkill",
  attached_equip = "surf_up",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)   
    local room = player.room 
    local players = {}
    local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase, true)
    if phase_event == nil then return false end
    room.logic:getEventsByRule(GameEvent.UseCard, 1, function (e)
      local use = e.data[1]
      if use.from == player.id then
        table.insertTableIfNeed(players, TargetGroup:getRealTargets(use.tos))
      end
      return false
    end, phase_event.id)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and not player:isAllNude() and #players == 1
    and not room:getPlayerById(table.unpack(players)).dead
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room 
    local players = {}
    local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase, true)
    if phase_event == nil then return false end
    room.logic:getEventsByRule(GameEvent.UseCard, 1, function (e)
      local use = e.data[1]
      if use.from == player.id then
        table.insertTableIfNeed(players, TargetGroup:getRealTargets(use.tos))
      end
      return false
    end, phase_event.id)
    player.room:setPlayerMark(player, "surfUpSkill_cards", player:getCardIds("j"))
    local success, dat = player.room:askForUseActiveSkill(player, "surfUpSkill_active", "#surfUpSkill_active::"..table.unpack(players), true)
    if success then
      self.cost_data = {cards = dat.cards, targets = table.unpack(players)}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:moveCardTo(self.cost_data.cards, Player.Hand, self.cost_data.targets, fk.ReasonGive, self.name, nil, true, player.id)
    local cards = player.room:getCardsFromPileByRule("jink", 1)
    if #cards > 0 and not player.dead then
      player.room:obtainCard(player, cards[1], false, fk.ReasonJustMove, player.id, self.name, "@@surfUp-inhand")
    end
  end,
}
local surfUpSkill_active = fk.CreateActiveSkill{
  name = "surfUpSkill_active",
  mute = true,
  min_card_num = 1,
  max_card_num = 1,
  target_num = 0,
  expand_pile = function(self)
    return Self:getTableMark("surfUpSkill_cards")
  end,
}
local surfUpSkillExclude = fk.CreateMaxCardsSkill{
  name = "#surfUpSkillExclude",
  global = true,
  exclude_from = function(self, player, card)
    return card and card:getMark("@@surfUp-inhand") ~= 0
  end,
}

local surf_up = fk.CreateWeapon{
  name = "&surf_up",
  suit = Card.Club,
  number = 3,
  attack_range = 2,
  equip_skill = surfUpSkill,
}

Fk:loadTranslationTable{
  ["surf_up"] = "冲浪时光",
  [":surf_up"] = "装备牌·武器<br /><b>攻击范围</b>：2<br /><b>武器技能</b>：出牌阶段结束时，若你本阶段仅对一名角色使用过牌，你可以将"..
  "区域内的一张牌交给其，获得一张不计入手牌上限的【闪】。",
  ["#surfUpSkill"] = "冲浪时光",
  ["surfUpSkill_active"] = "冲浪时光",
  ["@@surfUp-inhand"] = "冲浪时光",
  ["#surfUpSkill_active"] = "冲浪时光：是否将区域内一张牌交给%dest，获得一张不计入手牌上限的【闪】？",
}

extension:addCard(surf_up)
surfUpSkill:addRelatedSkill(tey__cangrong_destruct)
surfUpSkill:addRelatedSkill(surfUpSkillExclude)
Fk:addSkill(surfUpSkill)
Fk:addSkill(surfUpSkill_active)

local peakPatrolSongSkill = fk.CreateActiveSkill{
  name = "peakPatrolSongSkill",
  attached_equip = "peak_patrol_song",
  anim_type = "offensive",
  min_card_num = 0,
  max_card_num = 3,
  min_target_num = 0,
  max_target_num = 3,
  interaction = function(self)
    local all_choices
    if Self:usedSkillTimes(self.name, Player.HistoryGame) > 0 and Self:usedSkillTimes(self.name, Player.HistoryRound) == 0 then
      all_choices = {"ready_skill_resett", "ready_skill_check2"}
    elseif Self:usedSkillTimes(self.name, Player.HistoryGame) == 0 then
      all_choices = {"ready_skill_use", "ready_skill_check1"}
    else
      all_choices = {"ready_skill_check2"}
    end
    return UI.ComboBox {choices = all_choices}
  end,
  card_filter = function(self, to_select, selected)
    if self.interaction.data == "ready_skill_resett" then
    return #selected < 3 and not Self:prohibitDiscard(Fk:getCardById(to_select))
    else
    return false
    end
  end,
  target_filter = function(self, to_select, selected, selected_cards, extra_data, player)
    if self.interaction.data == "ready_skill_use" then
      return #selected < 3 and not Self:prohibitDiscard(Fk:getCardById(to_select))
      else
      return false
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    if self.interaction.data == "ready_skill_resett" then
      room:throwCard(effect.cards, self.name, player, player)
      player:setSkillUseHistory(self.name, 0, Player.HistoryGame)
      player:setSkillUseHistory(self.name, 0, Player.HistoryRound)
    elseif self.interaction.data == "ready_skill_use" then
      local nums = {}
      for _, p in ipairs(effect.tos) do
        if not room:getPlayerById(p).dead then
          room:getPlayerById(p):drawCards(1, self.name)
        end
      end
      for _, p in ipairs(effect.tos) do
        if not room:getPlayerById(p).dead then
          table.insert(nums, room:getPlayerById(p):getHandcardNum())
        end
      end
      local n = math.min(table.unpack(nums))
      if #table.filter(effect.tos, function (p) return not room:getPlayerById(p).dead and room:getPlayerById(p):getHandcardNum() == n end) ~= 1 then return end
      for _, p in ipairs(effect.tos) do
        if not room:getPlayerById(p).dead and room:getPlayerById(p):getHandcardNum() == n then
          room:setPlayerMark(room:getPlayerById(p), "@@peak_patrol_song_take", 1)
        end
      end
    end
  end,
  feasible = function (self, selected, selected_cards)
    return self.interaction.data ~= "ready_skill_check1" and self.interaction.data ~= "ready_skill_check2"
    and ((self.interaction.data == "ready_skill_resett" and #selected_cards == 3 and #selected == 0) 
    or (self.interaction.data == "ready_skill_use" and #selected_cards == 0 and #selected > 0))
  end,
}
local peakPatrolSongSkillTrigger = fk.CreateTriggerSkill{
  name = "#peakPatrolSongSkillTrigger",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if player:getMark("@@peak_patrol_song_take") > 0 then
      local cards = {}
      local card
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              card = Fk:getCardById(info.cardId, true)
              if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
              (card.type == Card.TypeBasic) then
                table.insertIfNeed(cards, info.cardId)
              end
            end
          elseif move.from == nil and (move.moveReason == fk.ReasonUse or move.moveReason == fk.ReasonResonpse) then
            local move_event = room.logic:getCurrentEvent()
            local parent_event = move_event.parent
            if parent_event ~= nil and (parent_event.event == GameEvent.UseCard or parent_event.event == GameEvent.RespondCard) then
              local parent_data = parent_event.data[1]
              if parent_data.from == player.id then
                local card_ids = room:getSubcardsByRule(parent_data.card)
                for _, info in ipairs(move.moveInfo) do
                  card = Fk:getCardById(info.cardId, true)
                  if table.contains(card_ids, info.cardId) and (card.type == Card.TypeBasic) then
                    table.insertIfNeed(cards, info.cardId)
                  end
                end
              end
            end
          end
        end
      end
      cards = table.filter(cards, function (id)
        return room:getCardArea(id) == Card.DiscardPile
      end)
      if #cards == 1 then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@peak_patrol_song_take", 0)
    room:moveCardTo(table.random(self.cost_data), Card.PlayerHand, player, fk.ReasonJustMove, self.name,
      nil, true, player.id)
  end,

  refresh_events = {fk.AfterDrawPileShuffle},
  can_refresh = function(self, event, target, player, data)
    return player:usedSkillTimes("peakPatrolSongSkill", Player.HistoryGame) > 0
  end,
  on_refresh = function(self, event, target, player, data)
    player:setSkillUseHistory("peakPatrolSongSkill", 0, Player.HistoryGame)
    player:setSkillUseHistory("peakPatrolSongSkill", 0, Player.HistoryRound)
  end,
}

local peak_patrol_song = fk.CreateWeapon{
  name = "&peak_patrol_song",
  suit = Card.Diamond,
  number = 7,
  attack_range = 2,
  equip_skill = peakPatrolSongSkill,
}

Fk:loadTranslationTable{
  ["peak_patrol_song"] = "岩峰巡歌",
  [":peak_patrol_song"] = "装备牌·武器<br /><b>攻击范围</b>：2<br /><b>武器技能</b>：蓄势技，出牌阶段，你可以令至多三名角色各摸一张牌。"..
  "其中手牌唯一最少的角色下次单张失去的基本牌进入弃牌堆后，其获得之。",
  ["peakPatrolSongSkill"] = "岩峰巡歌",
  [":peakPatrolSongSkill"] = "蓄势技，出牌阶段，你可以令至多三名角色各摸一张牌。其中手牌最少的角色下次单张失去的基本牌进入弃牌堆后，其获得之。",

  ["#peakPatrolSongSkillTrigger"] = "岩峰巡歌",
  ["ready_skill_resett"] = "岩峰巡歌：重置技能",
  ["ready_skill_use"] = "岩峰巡歌：发动技能",
  ["ready_skill_check1"] = "岩峰巡歌：可用",
  ["ready_skill_check2"] = "岩峰巡歌：蓄势中",

  ["@@peak_patrol_song_take"] = "岩巡 回收基本",
}

extension:addCard(peak_patrol_song)
peakPatrolSongSkill:addRelatedSkill(peakPatrolSongSkillTrigger)
peakPatrolSongSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(peakPatrolSongSkill)

local fangOfMountainKingSkill = fk.CreateTriggerSkill{
  name = "#fangOfMountainKingSkill",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and #player:getAvailableEquipSlots() > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local use = room:askForUseCard(player, self.name, ".|.|.|.|.|equip", "#fangOfMountainKingSkill-use", true, { bypass_distances = true , bypass_times = true })
    if use then
      use.extraUse = true
      room:useCard(use)
    else
      local toAbort = room:askForChoice(player, player:getAvailableEquipSlots(), self.name, "#fangOfMountainKingSkill-abort")
      if toAbort then
        for i = 1, #player:getAvailableEquipSlots(), 1 do --对不起了神吕布
          room:abortPlayerArea(player, toAbort)
        end
      end
    end
    --[[local subtypes = {Card.SubtypeWeapon, Card.SubtypeArmor, Card.SubtypeDefensiveRide, Card.SubtypeOffensiveRide, Card.SubtypeTreasure}
    local x = 0
    for i = 1, 5, 1 do
      if #player:getAvailableEquipSlots(subtypes[i]) > 0 and player:getEquipment(subtypes[i]) then
        x = x + 1
      end
    end]]
    local x = 1
    if x > 0 then
      local to = room:askForChoosePlayers(player, table.map(room:getAllPlayers(), Util.IdMapper), 1, 1,
      "#fangOfMountainKing-ask", self.name, false)
      if #to > 0 then
        local targetnil = room:getPlayerById(to[1])
        local card = room:askForCard(targetnil, 1, 1, false, self.name, true, ".", "#fangOfMountainKingSkill-give::"..player.id)
        if #card > 0 then
          room:obtainCard(player.id, card[1], false, fk.ReasonGive, to[1], self.name)
        else
          local skillnumber = table.map(table.filter(targetnil.player_skills, function (s)
            return s:isPlayerSkill(targetnil) and s.visible
          end), Util.NameMapper)
          local choice = room:askForChoices(player, skillnumber, 1, x, self.name, "#fangOfMountainKing-prompt:::"..x, false)
          for _, s in ipairs(choice) do
            room:invalidateSkill(targetnil, s, "-turn")
          end
        end
      end
    end
  end,
}

local fang_of_mountain_king = fk.CreateWeapon{
  name = "&fang_of_mountain_king",
  suit = Card.Club,
  number = 10,
  attack_range = 3,
  equip_skill = fangOfMountainKingSkill,
}

Fk:loadTranslationTable{
  ["fang_of_mountain_king"] = "山王长牙",
  [":fang_of_mountain_king"] = "装备牌·武器<br /><b>攻击范围</b>：3<br /><b>武器技能</b>：锁定技，准备阶段，你使用一张装备牌或废除一类装备栏，".. 
  "令一名角色选择一项：交给你一张手牌；或你令其一个技能本回合失效。",
  ["#fangOfMountainKingSkill"] = "山王长牙",
  ["#fangOfMountainKingSkill-use"] = "山王长牙：请使用一张装备牌，否则废除一个装备栏！",
  ["#fangOfMountainKingSkill-abort"] = "山王长牙：请废除一个装备栏！",
  ["#fangOfMountainKingSkill-give"] = "山王长牙：你需交给 %dest 一张手牌，否则其令你一个技能本回合失效！",
  ["#fangOfMountainKing-ask"] = "山王长牙：请选择一名角色，若其不交给你一张手牌，你便令其一个技能本回合失效！",
  ["#fangOfMountainKing-prompt"] = "山王长牙：请令其中%arg个技能本回合失效！",
}

extension:addCard(fang_of_mountain_king)
fangOfMountainKingSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(fangOfMountainKingSkill)

local vividNotionsSkill = fk.CreateTriggerSkill{
  name = "#vividNotionsSkill",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return target == player and #player:getTableMark("@vividNotions-turn") ~= 0 and player:getMark("vividNotions-turn") ~= 0 --不绑技能，以标记为准
    and data.card and not (data.card.type == Card.TypeEquip or data.card.trueName == "peach" or data.card.trueName == "analeptic")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if data.extra_data and data.extra_data.combo_skill then
      data.additionalEffect = (data.additionalEffect or 0) + 1
    else
      data.nullifiedTargets = table.map(room:getAlivePlayers(), Util.IdMapper)
    end
  end,

  refresh_events = {fk.TurnStart, fk.TurnEnd},
  can_refresh = function (self, event, target, player, data)
    return player:getMark("vividNotions-turn") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:handleAddLoseSkills(player, "-"..table.concat(player:getMark("vividNotions-turn"), "|-") , nil, true, false)
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    if #player:getTableMark("@vividNotions-turn") == 0 and player:getMark("vividNotions-turn") == 0 then
      local to = room:askForChoosePlayers(player, table.map(room:getAllPlayers(), Util.IdMapper), 1, 1,
      "#vividNotions-damage", self.name, false)
        if #to > 0 then
        room:damage{
          from = player,
          to = room:getPlayerById(to[1]),
          damage = 1,
          damageType = fk.ThunderDamage,
          skillName = self.name,
        }
        end
        if not player.dead then
          local available = {}
          for _, general in ipairs(room.general_pile) do
            local skills = Fk.generals[general]:getSkillNameList()
            for _, skill_name in ipairs(skills) do
              local skill = Fk.skills[skill_name]
                if
                  not player:hasSkill(skill.name, true)
                  and not skill.lordSkill 
                  and not skill.isHiddenSkill 
                  and not skill.CenterArea 
                  and #skill.attachedKingdom == 0 
                  and (Fk:getDescription(skill.name, "zh_CN"):startsWith("连招技") or skill.name == "rfenghou__pianshi")
                then
                table.insert(available, skill_name)
              end
            end
          end
        if Fk.skills["rfenghou__pianshi"] and not player:hasSkill("rfenghou__pianshi", true) then
          for i = 1, 12, 1 do
            table.insert(available, "rfenghou__pianshi") --先插几个谱韵玩玩
          end
        end
        if #available > 0 then
          local get = table.random(available, 1)
          room:setPlayerMark(player, "vividNotions-turn", get)
          room:handleAddLoseSkills(player, get, nil, true, false)
          room:addTableMark(player, "@vividNotions-turn", get[1])
        end
      end
    end
  end,
}

local vivid_notions = fk.CreateWeapon{
  name = "&vivid_notions",
  suit = Card.Diamond,
  number = 11,
  attack_range = 2,
  equip_skill = vividNotionsSkill,
}

Fk:loadTranslationTable{
  ["vivid_notions"] = "溢彩心念",
  [":vivid_notions"] = "装备牌·武器<br /><b>攻击范围</b>：2<br /><b>武器技能</b>：锁定技，此牌置入你的装备区后：<br>1.每回合限一次，你分配1点雷电伤害并于本回合获得一个连招技。".. 
  "<br>2.本回合你使用牌时（【桃】、【酒】或装备牌除外），若满足至少一个连招，则多结算一次，否则无效。",
  ["@vividNotions-turn"] = "溢彩心念",
  ["#vividNotionsSkill"] = "溢彩心念",
  [":#vividNotionsSkill"] = "锁定技，此牌置入你的装备区后：<br>1.每回合限一次，你分配1点雷电伤害并于本回合获得一个连招技。".. 
  "<br>2.本回合你使用牌时（【桃】、【酒】或装备牌除外），若满足至少一个连招，则多结算一次，否则无效。",
  ["#vividNotions-damage"] = "溢彩心念：请分配1点雷电伤害！",
}

extension:addCard(vivid_notions)
vividNotionsSkill:addRelatedSkill(tey__cangrong_destruct)
Fk:addSkill(vividNotionsSkill)

local tey__shadeSkill = fk.CreateActiveSkill{
  name = "tey__shade_skill",
  can_use = Util.FalseFunc,
}
local tey__shade = fk.CreateBasicCard{
  name = "&tey__shade",
  suit = Card.Spade,
  number = 1,
  skill = tey__shadeSkill,
}
extension:addCard(tey__shade)
Fk:loadTranslationTable{
  ["tey__shade"] = "影",
  [":tey__shade"] = "基本牌<br/><b>效果</b>：没有效果，不能被使用。<br/>当【影】进入弃牌堆后移出游戏。<br/>当一名角色获得【影】时，均为从游戏外获得♠A的【影】。<br>这张牌尚未迎来启封的时机...",
}

return extension
